package com.mobi.cacti.ns.view;

import java.util.ArrayList;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.ListView;

import com.mobi.cacti.R;
import com.mobi.cacti.ns.model.ListItem;
import com.mobi.cacti.ns.view.adapter.ItemListAdapter;
import com.mobi.cacti.ns.view.tab.BaseContainerFragment;
import com.mobi.cacti.rabbit.response.Cache;
import com.mobi.cacti.rabbit.response.GraphCircuit;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class GraphActivity extends Fragment {

	private String[] keySet;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = LayoutInflater.from(getActivity()).inflate(
				R.layout.graph_layout, null);
		
		ArrayList<ListItem> items = new ArrayList<ListItem>();
		keySet = new String[Cache.reqMobileLogin.responseCircuitIDWhenLogin.keySet().size()];
		keySet = Cache.reqMobileLogin.responseCircuitIDWhenLogin.keySet().toArray(keySet);
		
		for (String key : keySet) {
			ListItem item = new ListItem();
			item.label = "Circuit No. " + key;
			item.ticketCountLabel = null;
			item.isShowRightArrow = true;
			items.add(item);
		}
		
		ItemListAdapter adapter = new ItemListAdapter(getSupportActivity(), R.layout.rowitem_layout, items);
		ListView listView = (ListView) v.findViewById(R.id.graphlist);
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// init cache
				Cache.graphDetailStateBundle = new Bundle();
				
				String key = keySet[position];
				GraphCircuit graphCircuit = Cache.reqMobileLogin.responseCircuitIDWhenLogin.get(key);
				
				Bundle bundle = new Bundle();
				bundle.putParcelable("graphCircuit", graphCircuit);
				
				GraphDetailActivity graphDetailActivity = new GraphDetailActivity();
				graphDetailActivity.setArguments(bundle);
				
				((BaseContainerFragment)getParentFragment()).replaceFragment(graphDetailActivity, true);
			}
		});
		
		// check internet connection
		if (!Cache.isNetworkAvailable(getSupportActivity())) {
			// display alert dialog
			Cache.showNoInternetAlertDialog(getSupportActivity());
		}
		
		return v;
	}
}
